package com.yanqu.road.server.cmd.union;

import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.union.UnionJoinApplyMgr;
import com.yanqu.road.server.manger.union.UnionMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.utils.string.StringUtils;

//@Cmd(code = Protocol.S_UNION_JOIN, desc = "请求加入联盟")
public class JoinUnionCmd extends AbstractCommand {

	private String unionUid;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		UnionProto.UnionJoinReqMsg reqMsg = UnionProto.UnionJoinReqMsg.parseFrom(packet.getBytes());
		unionUid = reqMsg.getUnionUid();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		if(!SystemOpenMgr.systemOpen(player, eSystemId.Union.getValue())){
			ret = GameErrorCode.E_SYSTEM_NO_OPEN;
			return;
		}

		if (!StringUtils.isNullOrEmpty(player.getUserInfo().getUnionUid())) {
			ret = GameErrorCode.E_UNION_HAS_JOIN_UNION;
			return;
		}

		//重新加入联盟，需要判断时间
		long nowTime = System.currentTimeMillis() / 1000;
		UnionMember member = UnionMgr.getUnionMember("", player.getUserId());
		if(null != member && nowTime - member.getQuitTime() < GameConfig.UNION_NEXT_JOIN_NEED_TIME){
			ret = GameErrorCode.E_UNION_NEXT_JOIN_TIME_NO_ENOUGH;
			return;
		}

		if (!StringUtils.isNullOrEmpty(unionUid)) {
			ret = UnionJoinApplyMgr.addUnionJoinApply(player, unionUid);
		} else {
			ret = UnionMgr.randomJoin(player);
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		UnionProto.UnionJoinRespMsg.Builder respMsg = UnionProto.UnionJoinRespMsg.newBuilder();
		respMsg.setRet(ret);
		player.sendPacket(Protocol.U_UNION_JOIN, respMsg);
	}

}
